package com.jl.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Objects;

/**
 * @description ImageToBase64
 * @author guoyl@jinshanjf.com
 * @date 2019/7/4 0004
 * @version 1.0
 **/
@Slf4j
public class ImageToBase64 {

	private static String strNetImageToBase64;

//	public static void main(String[] args) {
//		//第一个:把网络图片装换成Base64
//		String netImagePath = "网络图片路径";
//		//下面是网络图片转换Base64的方法
//		//NetImageToBase64(netImagePath);
//
//		//下面是本地图片转换Base64的方法
//		String imagePath = "C:\\Users\\Administrator\\Documents\\WeChat Files\\gyl_develop\\FileStorage\\File\\2019-07\\微信图片_20190704141735.jpg";
//		ImageToBase64(imagePath);
//	}

	/**
	 * 网络图片转换Base64的方法
	 *
	 * @param netImagePath     
	 */
	public static String NetImageToBase64(String netImagePath) {
		String strNetImageToBase64 = null;
		final ByteArrayOutputStream data = new ByteArrayOutputStream();
		try {
			// 创建URL
			URL url = new URL(netImagePath);
			final byte[] by = new byte[1024];
			// 创建链接
			final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5000);
			InputStream is = conn.getInputStream();
			// 将内容读取内存中
			int len = -1;
			while ((len = is.read(by)) != -1) {
				data.write(by, 0, len);
			}
			// 对字节数组Base64编码
			strNetImageToBase64 = Base64.encodeBase64String(data.toByteArray());
			//log.debug("网络图片转换Base64:" + strNetImageToBase64);
			// 关闭流
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return strNetImageToBase64;
	}


	/**
	 * 本地图片转换Base64的方法
	 *
	 * @param imgPath     
	 */
	public static String ImageToBase64(String imgPath) {
		byte[] data = null;
		// 读取图片字节数组
		try {
			InputStream in = new FileInputStream(imgPath);
			data = new byte[in.available()];
			in.read(data);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return Base64.encodeBase64String(Objects.requireNonNull(data));
	}
}
